import 'package:flutter/material.dart';
import 'package:top_foundation/component/tabbar/controller.dart';
import 'package:top_foundation/utils/util.dart';

import '../component.dart';

class TPTabBarView extends StatefulWidget {
  const TPTabBarView({
    Key? key,
    required this.controller,
    required this.pageBuilder,
    this.height,
  }) : super(key: key);
  final TPTabBarController controller;
  final double? height;
  final NullableIndexedWidgetBuilder pageBuilder;
  @override
  State<TPTabBarView> createState() => _TPTabBarViewState();
}

class _TPTabBarViewState extends State<TPTabBarView> {
  @override
  void initState() {
    if (mounted) {
      widget.controller.actionTabItem(widget.controller.current);
    }
    super.initState();
  }

  Widget _buildContent() {
    return SizedBox(
      width: 1.sw,
      height: widget.height,
      child: PageView.builder(
        controller: widget.controller.pageCtrl,
        itemBuilder: (context, index) {
          if (widget.controller.current != index) {
            widget.controller.current = index;
          }
          return KeepAlivePage(
            child: widget.pageBuilder(context, index) ?? Container(),
          );
        },
        itemCount: widget.controller.titles.length,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildContent();
  }
}
